package com.xlf.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @param <T>
 */

public class TreeBuilder<T> {

    public List<T> buildTree(List<T> tree) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        ArrayList<T> res = new ArrayList<>();
        for (T node : tree) {
            Method getParentIdMethod = node.getClass().getMethod("getParentId");
            Long parentId = (Long) getParentIdMethod.invoke(node);

            // 判断是否是根节点
            if (parentId == null || parentId.equals(0L)) {
                // 递归拼装子节点
                res.add(buildSubTree(tree, node));
            }
        }
        return res;
    }

    private T buildSubTree(List<T> tree, T root) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method getIdMethod = root.getClass().getMethod("getId");
        Long rootId = (Long) getIdMethod.invoke(root);

        Method getChildrenMethod = root.getClass().getMethod("getChildren");
        List<T> children = (List<T>) getChildrenMethod.invoke(root);

        if (children == null) {
            children = new ArrayList<>();
        }

        for (T node : tree) {
            Method getParentIdMethod = node.getClass().getMethod("getParentId");
            Long parentId = (Long) getParentIdMethod.invoke(node);

            if (rootId.equals(parentId)) {
                children.add(buildSubTree(tree, node));
            }
        }

        return root;
    }

}
